// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
    dataList: [],
    wifiList: [],
    showAgain: false, //加载列表是否成功,
    IOStips: false,
    tips: false,
    token: wx.getStorageSync('token') || ''
  },
  // 事件处理函数
  
  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    this.setData({
      token: wx.getStorageSync('token') || ''
    });
  },
  onShow() {
    this.getIdentity();
    
  },
  getIdentity(){
    let that = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.login({
      success: res => {
        wx.request({
          url: 'https://test.cloudcampusapps.top:8080'+'/weChatWifiLogin/queryWeiUser'+'?flag=2'+'&code='+res.code,//请求的url
          header: {
            "Content-Type": "application/json",
            "token": wx.getStorageSync('token') || ''
          },
          method: "GET",
          success:function(res){
          if(res.data.code == 200) {
              wx.setStorageSync('token', res.data.data.Token);
              wx.getSystemInfo({
                success: (res)=> {
                  console.log('res.platform',res.platform)
                  if (res.platform == "ios") {   
                    that.setData({
                      IOStips: true
                    })
                    wx.hideLoading();
                    // setTimeout(function () {
                    //   that.bt_getwifi();
                    // }, 3000)
                  }else{  
                    that.bt_getwifi();
                  }
                }
              })
            }
            // wx.hideLoading();
          },
          fail:function(err){
            console.log('err=============='+err)
            wx.hideLoading()
          }
        })
      }
    })
    
  },
  bt_getwifi: function (res) {
    wx.showLoading({
      title: '加载中',
    })
    let that = this;
    wx.startWifi({
      success(res) {
        console.log("1、打开wifi成功", res)

        wx.onGetWifiList(function (res) {
          var newArr = res.wifiList.filter( res=>{
            return res.SSID.length != 0;
          })
          console.log("3、获取wifi列表成功", newArr)
          that.setData({
            wifiList: newArr,
            showAgain: false
          })
          that.getDataList();
        })

        wx.getWifiList({
          success(res) {
            console.log("2、获取wifi列表成功", res)
          },
          fail(res) {
            console.log("2、获取wifi列表失败(可能是没有开启位置权限)", res);
            wx.hideLoading();
            wx.showToast({
              title: that.errorStr(res.errCode),
              icon: 'error',
              duration: 2000
            })
            that.setData({
              showAgain: true
            })

            // 获取用户位置权限
            that.getLocationPermission().then(res => {
              if (res) {
                console.log("获取用户位置权限", res)
                wx.getWifiList({
                  success(res) {
                    console.log("2、获取wifi列表成功", res)
                  }
                })
              }
            })
          }
        })
      }
    })
  },
  errorStr: function (msg) {
    if (msg == "12001") return "当前系统不支持相关能力";
    if (msg == "12002") return "查不到账号，请联系系统管理员";
    if (msg == "12003") return "请确认是否在组织Wifi覆盖范围内";
    if (msg == "12004") return "重复连接Wifi";
    if (msg == "12005") return "未打开Wifi开关";
    if (msg == "12006") return "未打开GPS定位开关";
    if (msg == "12007") return "用户拒绝授权链接Wifi";
    if (msg == "12008") return "查不到账号，请联系系统管理员";
    if (msg == "12009") return "系统运行商配置拒绝链接Wifi";
    if (msg == "12010") return "未知错误，请联系系统管理员";
    if (msg == "12011") return "应用在后台无法配置Wifi";
    if (msg == "12013") return "查不到账号，请联系系统管理员";
    if (msg == "12014") return "";
  },
  getLocationPermission() {
    return new Promise(function (resolve, reject) {
      wx.getSetting({
        success(res) { // 1、查看所有权限
          let status = res.authSetting['scope.userLocation'] // 查看位置权限的状态，此处为初次请求，所以值为undefined
          console.log('查看位置权限状态：', status)
          if (!status) { // 如果是首次授权(undefined)或者之前拒绝授权(false)就会进入
            wx.authorize({ // 2、发起请求用户授权（用户点击了拒绝，之后是调不出获取权限对话框的，就会进入失败fail）
              scope: 'scope.userLocation',
              success() { // 用户允许了授权
                resolve(true)
              },

              fail(e) {
                console.log('用户之前拒绝过', e)
                wx.showModal({
                  title: '是否授权当前位置',
                  content: '需要获取您的地理位置，请确认授权，否则wifi功能将无法使用',
                  success: function (res) {
                    if (res.confirm) {
                      wx.openSetting({ //3、打开授权设置页面（这个要放在showModal里，不然会失败）
                        success(data) {
                          if (data.authSetting["scope.userLocation"] == true) {
                            wx.showToast({
                              title: '位置授权成功',
                              icon: 'success',
                              duration: 2000,
                              success() {}
                            })
                          } else {
                            console.log('从授权设置页面返回，用户不给授权')
                          }
                        },
                        fail(e) {
                          console.log('打开授权设置失败')
                          wx.showToast({
                            title: '位置授权失败，不能获取wifi列表',
                            icon: 'none',
                            duration: 2000,
                            success() {}
                          })
                        }
                      })
                    }

                  }
                })
              }
            })
          } else {
            console.log('用户之前授权过')
            resolve(true)
          }
        }
      })
    })
  },
  tryAgain() {
    this.getIdentity();
  },
  getDataList() {
    let that = this
    this.setData({
      IOStips: false
    })
    let params=[];
    for(let i=0;i<this.data.wifiList.length;i++){
      let obj = {
        ssid:this.data.wifiList[i].SSID,
        signalStrength:this.data.wifiList[i].signalStrength
      }
      params.push(obj)
    }
    wx.login({
      success: res => {
        wx.showLoading({
          title: '加载中',
        })
        wx.request({
          url: 'https://test.cloudcampusapps.top:8080/weChatWifiLogin/shopCustomer/queryShopLists?code='+res.code,
          header: {
            "Content-Type": "application/json",
            "token":  wx.getStorageSync('token') || ''
          },
          method: "POST",
          data: JSON.stringify(params),
          success:function(res){
            if(res.data.code == 200){
              let tips = false;
              if(res.data.data.length==0){
                wx.showToast({
                  title: '很抱歉，您所在区域暂不提供当前服务',
                  icon: 'none',
                  duration: 3000
                })
                tips = true;
              }else if(res.data.data.length===1) {
                let item = res.data.data[0];
                wx.navigateTo({
                  url: '../wifi/wifi?ssid='+item.ssidFlag+'_'+item.ssidName+'&pass='+item.ssidPassword+'&logo='+item.logoId+'&name='+item.shopName+'&imageSrc='+item.marketingId+'&id='+item.id
                })
              }
              that.setData({
                showAgain: false,
                dataList: res.data.data,
                tips:tips
              })
              wx.hideLoading();
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 2000
              })
              wx.hideLoading();
            }
          },
          fail:function(err){
            console.log('err=============='+err)
            wx.hideLoading()
          }
        })
      }
    })
  },
  clickDetails(e) {
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '../wifi/wifi?ssid='+item.ssidFlag+'_'+item.ssidName+'&pass='+item.ssidPassword+'&logo='+item.logoId+'&name='+item.shopName+'&imageSrc='+item.marketingId+'&id='+item.id
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        wx.setStorageSync('userInfo', res.userInfo); 
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    wx.setStorageSync('userInfo',  e.detail.userInfo); 
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  previewImage:function(e){
    wx.previewImage({
      current: "https://cloudcampusapps.top/wifilink/iosGuide/IOS.jpg", // 当前显示图片的http链接
      urls: ["https://cloudcampusapps.top/wifilink/iosGuide/IOS.jpg"], // 需要预览的图片http链接列表
    
    })
  }
})
